<template>
	<view class="restaurant-add-categories-container">
		<common-title :title="titleContent" @clickLeft="backToUpPage" @clickRight="clearaddCategoryInfo"></common-title>
		<view class="restaurant-add-category-form">
			<uni-forms ref="addCategoryForm" :modelValue="addCategoryFormData" :rules="addCategoryFromRules">
				<!-- 类别名：categoryName -->
				<uni-forms-item label="类别名" required name="categoryName">
					<uni-easyinput v-model="addCategoryFormData.categoryName" placeholder="请输入菜名"></uni-easyinput>
				</uni-forms-item>
				<!-- 是否上架：status -->
				<uni-forms-item label="状态" name="staus" required>
					<uni-data-checkbox v-model="addCategoryFormData.status" :localdata="categoryStatus"></uni-data-checkbox>
				</uni-forms-item>
				<!-- 类别排序：sort -->
				<uni-forms-item label="类别等级" name="sort" required>
					<uni-data-select
					      v-model="addCategoryFormData.sort"
					      :localdata="sort"
						  placeholder="请选择 (数字越小，优先级越高)"
					/>
				</uni-forms-item>
			</uni-forms>
			
			<!-- 底部操纵按钮 -->
			<view class="buttonOption">
			    <view 
			        class="addCategoryButton" 
			        @click="submit" 
			        :class="{'active': isPressedSub}" 
			        @touchstart="onPressSub" 
			        @touchend="onReleaseSub">
			        新增类别
			    </view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, onMounted } from 'vue';
	import { apiPostRestaurantCategory } from '@/utils/apiRestaurant.js'
	import { isLogin } from '../../../utils/apiMine';
	
	//===============================用户是否登录了=====================
	isLogin();
	//==============================标题===============================
	//标题内容
	const titleContent = ref({
		left:'返回',
		midst:'餐厅-新增类别',
		right: '清空'
	});
	//返回
	const backToUpPage = () => {
		uni.switchTab({
			url:'/pages/manage/manage'
		});
	};
	//清空新增类别数据
	const clearaddCategoryInfo = () => {
		addCategoryFormData.value = { ...initialFormData };
	};
	//==============================新增表单===============================
	
	// 表单引用
	const addCategoryForm = ref(null);
	
	// 表单数据
	// 定义初始状态
	const initialFormData = {
	    categoryName: '',
	    sort: null,
	    status: 1
	};
	
	// 创建 ref 对象
	const addCategoryFormData = ref({ ...initialFormData });
	
	// 表单验证规则
	const addCategoryFromRules = {
		categoryName: {
			rules: [
				{
					required: true,
					errorMessage: '类别名不能为空'
				},
				{
					minLength: 1,
					maxLength: 6,
					errorMessage: '类别名长度在 {minLength} 到 {maxLength} 个字符',
					validateFunction(rule, value, data, callback) {
						// 正则表达式定义为字符串
						const pricePattern = new RegExp('^(?=[^_])[\\u4e00-\\u9fa5A-Za-z0-9_]+$');
						
						if (!pricePattern.test(value)) {
							callback('只能是中文，字母，数字，下划线，且不能下划线开头');
						} else {
							callback(); // 校验通过
						}
					}
				}
			]
		},
		sort: {
			rules: [
				{
					required: true,
					errorMessage: '请选择类别'
				}
			]
		},
		status: {
			rules: [
				{
					required: true,
					errorMessage: '类别状态不能为空'
				}
			]
		}
	}
	
	//菜品类别状态
	const categoryStatus = ref([
		{text: '上架',value: 1}, 
		{text: '下架',value: 0}
	]);
	//类别排序
	const sort = ref([
		{text: '1',value: 1},
		{text: '2',value: 2},
		{text: '3',value: 3},
		{text: '4',value: 4},
		{text: '5',value: 5},
		{text: '6',value: 6},
		{text: '7',value: 7},
		{text: '8',value: 8},
		{text: '9',value: 9}
	]);
	
	// 在组件挂载时设置验证规则
	onMounted(() => {
		// console.log(addDishesForm.value)
	    addCategoryForm.value.setRules(addCategoryFromRules);
	});
	
	
	//-----------------------------------------底部按钮-------------------------------------
	const isPressedSub = ref(false);
	//点击新增按钮
	const onPressSub = () => {
		isPressedSub.value = true;
	};
	
	//长按新增按钮
	const onReleaseSub = () => {
		isPressedSub.value = false;
	};
	
	// 提交表单
	let isSubmitting = false; // 标志变量，初始化为 false
	const submit = async () => {
	    if (isSubmitting) return; // 如果正在提交，则直接返回
	    isSubmitting = true; // 设置为正在提交状态
	    try {
	        // 等待表单验证的结果
	        await addCategoryForm.value.validate();
			// 创建 FormData 实例
			const formData = new FormData();
			
			// 将表单数据添加到 FormData
			for (const key in addCategoryFormData.value) {
				formData.append(key, addCategoryFormData.value[key]);
			}
			// console.log(formData.get('status'));
	        let result = await apiPostRestaurantCategory(formData); // 确保这里使用 await
	
	        // 检查状态码（根据你的 API 返回调整条件）
	        if (result === '200') { // 此处假设 result 是一个字符串
	            uni.showToast({
	                title: "新增类别成功",
	                icon: 'success'
	            });
	        }
	    } catch (err) {
	        console.log('表单错误信息：', err); // 捕获验证和 API 调用中的错误
	    } finally {
			// TODO: 提交后清除表单信息等操作
			addCategoryFormData.value = { ...initialFormData };
	        isSubmitting = false; // 重置提交状态
	    }
	};
	
</script>

<style lang="scss" scoped>
	.restaurant-add-categories-container{
		.restaurant-add-category-form{
			padding: 30rpx;
		}
		.buttonOption{
			display: flex;
			align-items: center;
			justify-content: center;
			font-weight: bold;
			font-size: 36rpx;
			color: #000000 ;
			padding: 30rpx;
			.addCategoryButton{
				margin-top: 150rpx;
				width: 400rpx;
				height: 120rpx;
				border-radius: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: $brand-theme-color;
				box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.05);
			}
			.addCategoryButton.active {
			    background-color: #e4e4e4; /* 按下时的背景色 */
			    color: #999; /* 按下时的文字颜色 */
			}
		}
	}
</style>